// 云函数入口文件
const cloud = require('wx-server-sdk')
const tcbRouter = require('tcb-router')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 15
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new tcbRouter({event})
  //查询歌单
  app.router('getPlaylist',async(ctx,next)=>{
    ctx.body = await db.collection('playlist')
    .skip(event.start)
    .limit(event.count)
    .orderBy('createtime','desc')
    .get()
    .then((res)=>{
      return res
    })
  })
  //查询更多歌单
  app.router('getPlaylistMore',async(ctx,next)=>{
    ctx.body = await db.collection('playlist')
    .skip(event.start)
    .limit(event.count)
    .orderBy('createtime','desc')
    .get()
    .then((res)=>{
      return res
    })
  })
  //查询新歌
  app.router('getNewSongList',async(ctx,next)=>{
    ctx.body = await db.collection('newsong')
    .skip(event.start)
    .limit(event.count)
    .orderBy('createtime','desc')
    .get()
    .then((res)=>{
      return res.data
    })
  })
  
  //后台根据歌单ID查询歌曲
  app.router('getSongList',async(ctx,next)=>{
    let playlistId = event.playlistId
    ctx.body = await db.collection('songs')
    .where({
      playlistId
    })
    .skip(event.start)
    .limit(event.count)
    .orderBy('createtime','desc')
    .get()
    .then((res)=>{
      return res.data
    })
  })
  //小程序端根据歌单id 查找歌单下的所有音乐
  app.router('getMusiclist',async(ctx,next)=>{
     let playlistId = event.playlistId- 0;
     let detail= await db.collection('playlist').where({
      id:playlistId
    }).get().then(res=>{
       return res.data
    })
     let countResult = await db.collection('songs').count;
     let total = countResult.total;
      songlist = {
       data:[]
     }
    songlist = await db.collection('songs')
     .where({
       playlistId
     })
     .skip(event.start)
     .limit(event.count)
     .orderBy('createtime','asc')
     .get()
    ctx.body={
      detail,
      songlist,
      total
    }
  })
  //根据歌单ID,移除歌曲
 app.router('removeMusicOfPLaylist',async(ctx,next)=>{
  let playlistId = event.playlistId- 0;
  let res = await db.collection('songs').where({
    playlistId
  }).remove()
  ctx.body = {
    res
  }
 })
  //根据音乐id 查找音乐
  app.router('getMusicInfo',async(ctx,next)=>{
     let musicId = event.musicId - 0;
      ctx.body =await  db.collection('songs').where({
        musicId,
      }).get().then(res=>{
        return res.data
      })
  })


  //返回当前服务
  return app.serve();
}